package com.cq.hd.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.TbBusinessSubscribeApi;
import com.cq.hd.member.api.vo.BusinessSubscribeVo;
import com.cq.hd.member.api.vo.BusinessVo;
import com.cq.hd.product.api.dto.IndexActivePageDto;
import com.cq.hd.product.api.dto.SearchDto;
import com.cq.hd.product.api.dto.SearchRecordPageDto;
import com.cq.hd.product.api.vo.*;
import com.cq.hd.product.po.TbSearchRecordPo;
import com.cq.hd.product.mapper.TbSearchRecordMapper;
import com.cq.hd.product.service.TbActiveService;
import com.cq.hd.product.service.TbSearchRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 历史搜索表 服务实现类
 * </p>
 *
 * @author mYunYu
 * @since 2023-11-23
 */
@Service
public class TbSearchRecordServiceImpl extends ServiceImpl<TbSearchRecordMapper, TbSearchRecordPo> implements TbSearchRecordService {

    @Autowired
    private TbActiveService tbActiveService;

    @Autowired
    private TbBusinessApi businessApi;

    @Autowired
    private TbBusinessSubscribeApi businessSubscribeApi;

    @Override
    public Page<SearchRecordPageVo> pageSearchRecord(SearchRecordPageDto searchRecordPageDto) {
        PageHelper.startPage(searchRecordPageDto.getPageNum(), searchRecordPageDto.getPageSize());
        List<SearchRecordPageVo> searchRecordPageVos = baseMapper.listSearchRecordByDto(searchRecordPageDto);
        PageInfo<SearchRecordPageVo> pageInfo = new PageInfo<>(searchRecordPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public Object search(SearchDto searchDto) {
        String keyword = searchDto.getKeyword();
        Long userId = searchDto.getUserId();
        if (userId != null && userId > 0) {
            List<TbSearchRecordPo> tbSearchRecordPos = baseMapper.selectList(new QueryWrapper<TbSearchRecordPo>()
                    .eq("del_state", 0)
                    .eq("user_id", userId)
                    .eq("keyword", keyword));
            if (CollectionUtils.isEmpty(tbSearchRecordPos)) {
                // 新增搜索记录
                TbSearchRecordPo tbSearchRecordPo = new TbSearchRecordPo();
                tbSearchRecordPo.setUserId(userId);
                tbSearchRecordPo.setKeyword(keyword);
                tbSearchRecordPo.setSearchTime(LocalDateTime.now());
                tbSearchRecordPo.setCreateTime(LocalDateTime.now());
                baseMapper.insert(tbSearchRecordPo);
            } else {
                TbSearchRecordPo tbSearchRecordPo = tbSearchRecordPos.get(0);
                tbSearchRecordPo.setSearchTime(LocalDateTime.now());
                tbSearchRecordPo.setUpdateTime(LocalDateTime.now());
                baseMapper.updateById(tbSearchRecordPo);
            }
        }

        // 搜索类型：1-活动，2-商家
        Integer type = searchDto.getType();
        if (type == null || type == 1) {
            // 查询活动
            IndexActivePageDto indexActivePageDto = new IndexActivePageDto();
            indexActivePageDto.setActiveTitle(keyword);
            indexActivePageDto.setUserId(searchDto.getUserId());
            indexActivePageDto.setType(type == null ? 1 : type);
            return tbActiveService.pageIndexActive(indexActivePageDto);
        } else if (type == 2) {
            List<SearchBusinessVo> searchBusinessVos = new ArrayList<>();

            // 查询商家
            Page<BusinessVo> businessVoPage = businessApi.searchByBusinessName(searchDto.getPageNum(), searchDto.getPageSize(), searchDto.getKeyword()).unpack();
            List<BusinessVo> businessVos = businessVoPage.getList();
            if (!CollectionUtils.isEmpty(businessVos)) {
                List<Long> businessIds = businessVos.stream().map(BusinessVo::getId).collect(Collectors.toList());

                // 查询商家订阅列表
                Map<Long, List<BusinessSubscribeVo>> businessSubscribeMap = new HashMap<>();
                List<BusinessSubscribeVo> businessSubscribeVos = businessSubscribeApi.listByBusinessIds(businessIds).unpack();
                if (!CollectionUtils.isEmpty(businessSubscribeVos)) {
                    businessSubscribeMap = businessSubscribeVos.stream().collect(Collectors.groupingBy(BusinessSubscribeVo::getBusinessId));
                }

                // 查询商家进行中的活动列表
                Map<Long, List<SearchBusinessActiveVo>> searchBusinessActiveMap = new HashMap<>();
                List<SearchBusinessActiveVo> searchBusinessActives = tbActiveService.listSearchBusinessActive(businessIds);
                if (!CollectionUtils.isEmpty(searchBusinessActives)) {
                    searchBusinessActiveMap = searchBusinessActives.stream().collect(Collectors.groupingBy(SearchBusinessActiveVo::getBusinessId));
                }

                for (BusinessVo businessVo : businessVos) {
                    SearchBusinessVo searchBusinessVo = new SearchBusinessVo();
                    searchBusinessVo.setBusinessId(businessVo.getId());
                    searchBusinessVo.setBusinessName(businessVo.getBusinessName());
                    searchBusinessVo.setBusinessShortName(businessVo.getBusinessShortName());
                    searchBusinessVo.setLogo(businessVo.getLogo());
                    searchBusinessVo.setProvinceName(businessVo.getProvinceName());
                    searchBusinessVo.setCityName(businessVo.getCityName());
                    searchBusinessVo.setCountyName(businessVo.getCountyName());
                    searchBusinessVo.setAddress(businessVo.getPosition());

                    List<BusinessSubscribeVo> businessSubscribeVoList = businessSubscribeMap.get(businessVo.getId());
                    if (!CollectionUtils.isEmpty(businessSubscribeVoList)) {
                        searchBusinessVo.setSubscribeCount(businessSubscribeVoList.size());
                    }

                    List<SearchBusinessActiveVo> searchBusinessActiveVos = searchBusinessActiveMap.get(businessVo.getId());
                    if (!CollectionUtils.isEmpty(searchBusinessActiveVos)) {
                        searchBusinessVo.setActiveCount(searchBusinessActiveVos.size());
                        if (searchBusinessActiveVos.size() > 3) {
                            searchBusinessActiveVos = searchBusinessActiveVos.subList(0, 3);
                        }

                        searchBusinessVo.setSearchBusinessActives(searchBusinessActiveVos);
                    }

                    searchBusinessVos.add(searchBusinessVo);
                }
            }

            return Page.newPageWithAllFields(searchBusinessVos, businessVoPage.getPageNum(), businessVoPage.getPageSize(), businessVoPage.getTotal(), businessVoPage.getPages());
        }

        return null;
    }

    @Override
    public Boolean deleteSearchRecord(Long userId, Long id) {
        if (id == null || id <= 0) {
            baseMapper.delete(new QueryWrapper<TbSearchRecordPo>().eq("user_id", userId));
        } else {
            baseMapper.delete(new QueryWrapper<TbSearchRecordPo>()
                    .eq("id", id).eq("user_id", userId));
        }

        return true;
    }
}
